import 'package:get/get.dart';

/// 睡眠页状态管理
class SleepState {
  /// 是否正在记录
  RxBool isRecording = false.obs;
  
  /// 睡眠文本
  RxString sleepText = '睡眠页面'.obs;
  
  /// 开始时间
  Rx<DateTime> startTime = DateTime.now().obs;
  
  /// 睡眠时长
  RxString duration = ''.obs;
  
  /// 睡眠质量
  RxString quality = '良好'.obs;

  // 日视图数据
  /// 每日睡眠评分
  RxInt dailySleepScore = 67.obs;
  
  /// 每日睡眠时长
  RxString dailySleepTime = '6小时11分'.obs;
  
  /// 每日在床时间
  RxString dailyBedTime = '6小时11分'.obs;
  
  /// 每日入睡潜伏期（分钟）
  RxInt dailySleepLatency = 0.obs;

  // 周视图数据
  /// 本周平均睡眠评分
  RxInt weeklySleepScore = 72.obs;
  
  /// 本周平均睡眠时长
  RxString weeklySleepTime = '6小时45分'.obs;
  
  /// 本周平均在床时间
  RxString weeklyBedTime = '7小时30分'.obs;
  
  /// 本周平均入睡潜伏期（分钟）
  RxInt weeklySleepLatency = 12.obs;

  // 月视图数据
  /// 本月平均睡眠评分
  RxInt monthlySleepScore = 69.obs;
  
  /// 本月平均睡眠时长
  RxString monthlySleepTime = '6小时28分'.obs;
  
  /// 本月平均在床时间
  RxString monthlyBedTime = '7小时15分'.obs;
  
  /// 本月平均入睡潜伏期（分钟）
  RxInt monthlySleepLatency = 15.obs;

  // 睡眠详情数据
  /// 睡眠信息数据
  Rxn<SleepInfoData> sleepInfoData = Rxn<SleepInfoData>();
  
  /// 睡眠质量评分数据
  Rxn<SleepQualityScoreData> sleepQualityData = Rxn<SleepQualityScoreData>();
  
  /// 睡眠比例数据
  Rxn<SleepProportionData> sleepProportionData = Rxn<SleepProportionData>();
  
  /// 睡眠活动状态数据
  Rxn<SleepActivityStatusData> sleepActivityData = Rxn<SleepActivityStatusData>();
  
  /// 睡眠趋势数据（近7日）
  Rxn<SleepTrendData> sleepTrendData = Rxn<SleepTrendData>();
  
  /// 睡眠心率数据
  Rxn<SleepMetricData> sleepHeartRateData = Rxn<SleepMetricData>();
  
  /// 睡眠心率变异性数据
  Rxn<SleepMetricData> sleepHrvData = Rxn<SleepMetricData>();
  
  /// 睡眠血氧数据
  Rxn<SleepMetricData> sleepBloodOxygenData = Rxn<SleepMetricData>();

  /// 小睡数据
  Rxn<ShortSleepData> shortSleepData = Rxn<ShortSleepData>();

  /// 周/月睡眠详情数据
  Rxn<WeekMonthSleepDetailData> weekMonthSleepDetailData = Rxn<WeekMonthSleepDetailData>();

  /// 更新睡眠信息数据
  void updateSleepInfoData(SleepInfoData data) {
    sleepInfoData.value = data;
  }
  
  /// 更新周/月睡眠详情数据
  void updateWeekMonthSleepDetailData(WeekMonthSleepDetailData data) {
    weekMonthSleepDetailData.value = data;
  }
  
  /// 更新小睡数据
  void updateShortSleepData(ShortSleepData data) {
    shortSleepData.value = data;
  }
  
  /// 更新睡眠趋势数据
  void updateSleepTrendData(SleepTrendData data) {
    sleepTrendData.value = data;
  }

  /// 更新睡眠质量评分数据
  void updateSleepQualityData(SleepQualityScoreData data) {
    sleepQualityData.value = data;
    // 同时更新每日评分
    dailySleepScore.value = data.sleepScore;
  }

  /// 更新睡眠比例数据
  void updateSleepProportionData(SleepProportionData data) {
    sleepProportionData.value = data;
  }

  /// 更新睡眠活动状态数据
  void updateSleepActivityData(SleepActivityStatusData data) {
    sleepActivityData.value = data;
  }
  
  /// 更新睡眠心率数据
  void updateSleepHeartRateData(SleepMetricData data) {
    sleepHeartRateData.value = data;
  }
  
  /// 更新睡眠心率变异性数据
  void updateSleepHrvData(SleepMetricData data) {
    sleepHrvData.value = data;
  }
  
  /// 更新睡眠血氧数据
  void updateSleepBloodOxygenData(SleepMetricData data) {
    sleepBloodOxygenData.value = data;
  }
}

/// 睡眠信息数据模型
class SleepInfoData {
  final String deviceSn;
  final String sleepType;
  final String dailyValue;
  final String startDate;
  final String endDate;
  final int sleepDurationMinute;
  final String sleepDuration;
  final String? longSleepDuration;
  final String? shortSleepDuration;
  final String? shortSleepStartTime;
  final String? shortSleepEndTime;
  final Map<String, List<SleepStageSegment>>? maps;
  final int sleepTime;
  final int totalTime;
  final int sleepScore;
  final int sleepEfficiency;
  
  // 周/月视图专用字段
  final String? average; // 平均总睡眠时长
  final String? dateStart; // 开始日期（周/月）
  final String? dateEnd; // 结束日期（周/月）
  final String? longAverage; // 平均睡眠（周/月）
  final String? shortAverage; // 平均小睡（周/月）
  final List<DailySleepDetail>? ringWeekOrMonthSleepVOS; // 每日睡眠详情列表

  SleepInfoData({
    required this.deviceSn,
    required this.sleepType,
    required this.dailyValue,
    required this.startDate,
    required this.endDate,
    required this.sleepDurationMinute,
    required this.sleepDuration,
    this.longSleepDuration,
    this.shortSleepDuration,
    this.shortSleepStartTime,
    this.shortSleepEndTime,
    this.maps,
    required this.sleepTime,
    required this.totalTime,
    required this.sleepScore,
    required this.sleepEfficiency,
    this.average,
    this.dateStart,
    this.dateEnd,
    this.longAverage,
    this.shortAverage,
    this.ringWeekOrMonthSleepVOS,
  });

  factory SleepInfoData.fromJson(Map<String, dynamic> json) {
    Map<String, List<SleepStageSegment>>? parsedMaps;
    if (json['maps'] != null && json['maps'] is Map) {
      parsedMaps = {};
      (json['maps'] as Map).forEach((key, value) {
        if (value is List) {
          parsedMaps![key.toString()] = (value as List)
              .map((item) => SleepStageSegment.fromJson(item as Map<String, dynamic>))
              .toList();
        }
      });
    }

    // 解析周/月视图的每日睡眠详情列表
    List<DailySleepDetail>? weekOrMonthSleeps;
    if (json['ringWeekOrMonthSleepVOS'] != null && json['ringWeekOrMonthSleepVOS'] is List) {
      weekOrMonthSleeps = [];
      for (var item in json['ringWeekOrMonthSleepVOS']) {
        if (item != null && item is Map<String, dynamic>) {
          weekOrMonthSleeps.add(DailySleepDetail.fromJson(item));
        }
      }
    }

    return SleepInfoData(
      deviceSn: json['deviceSn']?.toString() ?? '',
      sleepType: json['sleepType']?.toString() ?? '',
      dailyValue: json['dailyValue']?.toString() ?? '',
      startDate: json['startDate']?.toString() ?? '',
      endDate: json['endDate']?.toString() ?? '',
      sleepDurationMinute: json['sleepDurationMinute'] ?? 0,
      sleepDuration: json['sleepDuration']?.toString() ?? '--',
      longSleepDuration: json['longSleepDuration']?.toString(),
      shortSleepDuration: json['shortSleepDuration']?.toString(),
      shortSleepStartTime: json['shortSleepStartTime']?.toString(),
      shortSleepEndTime: json['shortSleepEndTime']?.toString(),
      maps: parsedMaps,
      sleepTime: json['sleepTime'] ?? 0,
      totalTime: json['totalTime'] ?? 0,
      sleepScore: json['sleepScore'] ?? 0,
      sleepEfficiency: json['sleepEfficiency'] ?? 0,
      average: json['average']?.toString(),
      dateStart: json['dateStart']?.toString(),
      dateEnd: json['dateEnd']?.toString(),
      longAverage: json['longAverage']?.toString(),
      shortAverage: json['shortAverage']?.toString(),
      ringWeekOrMonthSleepVOS: weekOrMonthSleeps,
    );
  }
}

/// 睡眠阶段片段
class SleepStageSegment {
  final String startTime;
  final String endTime;
  final int totalTime;
  final int sleepType;

  SleepStageSegment({
    required this.startTime,
    required this.endTime,
    required this.totalTime,
    required this.sleepType,
  });

  factory SleepStageSegment.fromJson(Map<String, dynamic> json) {
    return SleepStageSegment(
      startTime: json['startTime']?.toString() ?? '',
      endTime: json['endTime']?.toString() ?? '',
      totalTime: json['totalTime'] ?? 0,
      sleepType: json['sleepType'] ?? 0,
    );
  }
}

/// 睡眠质量评分数据模型
class SleepQualityScoreData {
  final int sleepScore;
  final String sleepDuration;
  final int sleepEfficiency;
  final int sleepLatency;
  final String timing;
  final String sleepValue;
  final String summary;

  SleepQualityScoreData({
    required this.sleepScore,
    required this.sleepDuration,
    required this.sleepEfficiency,
    required this.sleepLatency,
    required this.timing,
    required this.sleepValue,
    required this.summary,
  });

  factory SleepQualityScoreData.fromJson(Map<String, dynamic> json) {
    return SleepQualityScoreData(
      sleepScore: json['sleepScore'] ?? 0,
      sleepDuration: json['sleepDuration']?.toString() ?? '--',
      sleepEfficiency: json['sleepEfficiency'] ?? 0,
      sleepLatency: json['sleepLatency'] ?? 0,
      timing: json['timing']?.toString() ?? '--',
      sleepValue: json['sleepValue']?.toString() ?? '',
      summary: json['summary']?.toString() ?? '',
    );
  }
}

/// 睡眠比例数据模型
class SleepProportionData {
  final SleepStageProportionItem? awake; // 0: 清醒
  final SleepStageProportionItem? light; // 1: 浅睡眠
  final SleepStageProportionItem? deep; // 2: 深睡眠
  final SleepStageProportionItem? rem; // 3: 快速眼动

  SleepProportionData({
    this.awake,
    this.light,
    this.deep,
    this.rem,
  });

  factory SleepProportionData.fromJson(Map<String, dynamic> json) {
    return SleepProportionData(
      awake: json['0'] != null ? SleepStageProportionItem.fromJson(json['0']) : null,
      light: json['1'] != null ? SleepStageProportionItem.fromJson(json['1']) : null,
      deep: json['2'] != null ? SleepStageProportionItem.fromJson(json['2']) : null,
      rem: json['3'] != null ? SleepStageProportionItem.fromJson(json['3']) : null,
    );
  }
}

/// 睡眠阶段比例项
class SleepStageProportionItem {
  final int proportion;
  final String sleepDuration;
  final String? rateValue; // 评价值：偏少/适中/偏多

  SleepStageProportionItem({
    required this.proportion,
    required this.sleepDuration,
    this.rateValue,
  });

  factory SleepStageProportionItem.fromJson(Map<String, dynamic> json) {
    return SleepStageProportionItem(
      proportion: json['proportion'] ?? 0,
      sleepDuration: json['sleepDuration']?.toString() ?? '0小时0分钟',
      rateValue: json['rateValue']?.toString(),
    );
  }
}

/// 睡眠活动状态数据模型
class SleepActivityStatusData {
  final String sleepStartDate;
  final String sleepEndDate;
  final String sleepTime;
  final String soberTime;
  final List<ActivityTypeGroup> activityStatusList;

  SleepActivityStatusData({
    required this.sleepStartDate,
    required this.sleepEndDate,
    required this.sleepTime,
    required this.soberTime,
    required this.activityStatusList,
  });

  factory SleepActivityStatusData.fromJson(Map<String, dynamic> json) {
    final List<ActivityTypeGroup> activities = [];
    if (json['activityStatusList'] != null && json['activityStatusList'] is List) {
      for (var item in json['activityStatusList']) {
        if (item != null && item is Map<String, dynamic>) {
          activities.add(ActivityTypeGroup.fromJson(item));
        }
      }
    }

    return SleepActivityStatusData(
      sleepStartDate: json['sleepStartDate']?.toString() ?? '',
      sleepEndDate: json['sleepEndDate']?.toString() ?? '',
      sleepTime: json['sleepTime']?.toString() ?? '',
      soberTime: json['soberTime']?.toString() ?? '',
      activityStatusList: activities,
    );
  }
}

/// 活动类型分组
class ActivityTypeGroup {
  final String activityType;
  final List<ActivityPoint> activityStatusList;

  ActivityTypeGroup({
    required this.activityType,
    required this.activityStatusList,
  });

  factory ActivityTypeGroup.fromJson(Map<String, dynamic> json) {
    final List<ActivityPoint> points = [];
    if (json['activityStatusList'] != null && json['activityStatusList'] is List) {
      for (var item in json['activityStatusList']) {
        if (item != null && item is Map<String, dynamic>) {
          points.add(ActivityPoint.fromJson(item));
        }
      }
    }

    return ActivityTypeGroup(
      activityType: json['activityType']?.toString() ?? '',
      activityStatusList: points,
    );
  }
}

/// 活动数据点
class ActivityPoint {
  final String key; // 时间点
  final int value; // 活动值

  ActivityPoint({
    required this.key,
    required this.value,
  });

  factory ActivityPoint.fromJson(Map<String, dynamic> json) {
    return ActivityPoint(
      key: json['key']?.toString() ?? '',
      value: json['value'] ?? 0,
    );
  }
}

/// 睡眠趋势数据模型
class SleepTrendData {
  final String sleepDuration;
  final List<DailySleepTrend> chart;

  SleepTrendData({
    required this.sleepDuration,
    required this.chart,
  });

  factory SleepTrendData.fromJson(Map<String, dynamic> json) {
    final List<DailySleepTrend> chartList = [];
    if (json['chart'] != null && json['chart'] is List) {
      for (var item in json['chart']) {
        if (item != null && item is Map<String, dynamic>) {
          chartList.add(DailySleepTrend.fromJson(item));
        }
      }
    }

    return SleepTrendData(
      sleepDuration: json['sleepDuration']?.toString() ?? '--',
      chart: chartList,
    );
  }
}

/// 每日睡眠趋势
class DailySleepTrend {
  final String dailyValue; // 日期 "2025-10-19"
  final List<SleepStageValue> trendList; // [清醒, 浅睡眠, 深睡眠, 快速眼动]

  DailySleepTrend({
    required this.dailyValue,
    required this.trendList,
  });

  factory DailySleepTrend.fromJson(Map<String, dynamic> json) {
    final List<SleepStageValue> trends = [];
    if (json['trendList'] != null && json['trendList'] is List) {
      for (var item in json['trendList']) {
        if (item != null && item is Map<String, dynamic>) {
          trends.add(SleepStageValue.fromJson(item));
        }
      }
    }

    return DailySleepTrend(
      dailyValue: json['dailyValue']?.toString() ?? '',
      trendList: trends,
    );
  }
  
  // 获取各阶段时长（分钟转小时）
  // trendList 顺序: [0]=awake(清醒), [1]=rem(快速眼动), [2]=light(浅睡眠), [3]=deep(深睡眠)
  double get awakeHours => trendList.isNotEmpty ? trendList[0].value / 60.0 : 0;
  double get remHours => trendList.length > 1 ? trendList[1].value / 60.0 : 0;
  double get lightHours => trendList.length > 2 ? trendList[2].value / 60.0 : 0;
  double get deepHours => trendList.length > 3 ? trendList[3].value / 60.0 : 0;
}

/// 睡眠阶段值
class SleepStageValue {
  final int value; // 分钟数

  SleepStageValue({
    required this.value,
  });

  factory SleepStageValue.fromJson(Map<String, dynamic> json) {
    return SleepStageValue(
      value: json['value'] ?? 0,
    );
  }
}

/// 睡眠指标数据模型（心率、心率变异性、血氧）
class SleepMetricData {
  final int average; // 平均值
  final int maxValue; // 最大值
  final int minValue; // 最小值
  final String? startDate; // 开始日期
  final String? endDate; // 结束日期
  final List<MetricDataPoint> dataList; // 数据点列表（日视图）
  final List<MetricDateRange>? longSleepDates; // 周/月视图数据列表

  SleepMetricData({
    required this.average,
    required this.maxValue,
    required this.minValue,
    this.startDate,
    this.endDate,
    required this.dataList,
    this.longSleepDates,
  });

  factory SleepMetricData.fromJson(Map<String, dynamic> json) {
    final List<MetricDataPoint> points = [];
    
    // 根据不同的字段名解析数据列表（日视图）
    List<dynamic>? dataListJson;
    if (json['heartRateList'] != null) {
      dataListJson = json['heartRateList'] as List<dynamic>;
    } else if (json['hrvList'] != null) {
      dataListJson = json['hrvList'] as List<dynamic>;
    } else if (json['boList'] != null) {
      dataListJson = json['boList'] as List<dynamic>;
    }
    
    if (dataListJson != null) {
      for (var item in dataListJson) {
        if (item != null && item is Map<String, dynamic>) {
          points.add(MetricDataPoint.fromJson(item));
        }
      }
    }

    // 解析周/月视图数据
    List<MetricDateRange>? longSleepDates;
    if (json['longSleepDates'] != null && json['longSleepDates'] is List) {
      longSleepDates = [];
      for (var item in json['longSleepDates']) {
        if (item != null && item is Map<String, dynamic>) {
          longSleepDates.add(MetricDateRange.fromJson(item));
        }
      }
    }

    return SleepMetricData(
      average: json['average'] ?? 0,
      maxValue: json['maxValue'] ?? 0,
      minValue: json['minValue'] ?? 0,
      startDate: json['startDate']?.toString(),
      endDate: json['endDate']?.toString(),
      dataList: points,
      longSleepDates: longSleepDates,
    );
  }
}

/// 指标数据点
class MetricDataPoint {
  final String key; // 时间点 "01:00"
  final int value; // 数值

  MetricDataPoint({
    required this.key,
    required this.value,
  });

  factory MetricDataPoint.fromJson(Map<String, dynamic> json) {
    return MetricDataPoint(
      key: json['key']?.toString() ?? '',
      value: json['value'] ?? 0,
    );
  }
}

/// 指标日期范围数据（周/月视图）
class MetricDateRange {
  final String dailyValue; // 日期值 "11/16"
  final MetricRangeInfo? rangeInfo; // 指标范围信息（统一字段名）

  MetricDateRange({
    required this.dailyValue,
    this.rangeInfo,
  });

  factory MetricDateRange.fromJson(Map<String, dynamic> json) {
    // API 对所有指标都使用 longSleepRateInfo 字段名
    return MetricDateRange(
      dailyValue: json['dailyValue']?.toString() ?? '',
      rangeInfo: json['longSleepRateInfo'] != null
          ? MetricRangeInfo.fromJson(json['longSleepRateInfo'])
          : null,
    );
  }
  
  // 兼容性访问器
  MetricRangeInfo? get longSleepRateInfo => rangeInfo;
  MetricRangeInfo? get longSleepHrvInfo => rangeInfo;
  MetricRangeInfo? get longSleepBoInfo => rangeInfo;
}

/// 指标范围信息
class MetricRangeInfo {
  final int maxValue; // 最大值
  final int minValue; // 最小值

  MetricRangeInfo({
    required this.maxValue,
    required this.minValue,
  });

  factory MetricRangeInfo.fromJson(Map<String, dynamic> json) {
    return MetricRangeInfo(
      maxValue: json['maxValue'] ?? 0,
      minValue: json['minValue'] ?? 0,
    );
  }
}

/// 小睡数据模型
class ShortSleepData {
  final String sleepDuration; // 平均小睡时长 "0小时18分"
  final List<ShortSleepDate> shortSleepDates; // 小睡日期列表

  ShortSleepData({
    required this.sleepDuration,
    required this.shortSleepDates,
  });

  factory ShortSleepData.fromJson(Map<String, dynamic> json) {
    final List<ShortSleepDate> dates = [];
    if (json['shortSleepDates'] != null && json['shortSleepDates'] is List) {
      for (var item in json['shortSleepDates']) {
        if (item != null && item is Map<String, dynamic>) {
          dates.add(ShortSleepDate.fromJson(item));
        }
      }
    }

    return ShortSleepData(
      sleepDuration: json['sleepDuration']?.toString() ?? '0小时0分',
      shortSleepDates: dates,
    );
  }
}

/// 小睡日期数据
class ShortSleepDate {
  final String dailyValue; // 日期值，根据type不同格式不同
  final List<ShortSleepTime>? shortSleepTimes; // 小睡时间段列表，可能为null

  ShortSleepDate({
    required this.dailyValue,
    this.shortSleepTimes,
  });

  factory ShortSleepDate.fromJson(Map<String, dynamic> json) {
    List<ShortSleepTime>? times;
    if (json['shortSleepTimes'] != null && json['shortSleepTimes'] is List) {
      times = [];
      for (var item in json['shortSleepTimes']) {
        if (item != null && item is Map<String, dynamic>) {
          times.add(ShortSleepTime.fromJson(item));
        }
      }
    }

    return ShortSleepDate(
      dailyValue: json['dailyValue']?.toString() ?? '',
      shortSleepTimes: times,
    );
  }
}

/// 小睡时间段
class ShortSleepTime {
  final String startDate; // 开始时间 "13:15"
  final String endDate; // 结束时间 "13:33"

  ShortSleepTime({
    required this.startDate,
    required this.endDate,
  });

  factory ShortSleepTime.fromJson(Map<String, dynamic> json) {
    return ShortSleepTime(
      startDate: json['startDate']?.toString() ?? '',
      endDate: json['endDate']?.toString() ?? '',
    );
  }
}


/// 周/月睡眠详情数据模型
class WeekMonthSleepDetailData {
  final String average; // 平均总睡眠时长 "4小时14分"
  final String dateStart; // 开始日期 "2025年11月16日，周日"
  final String dateEnd; // 结束日期 "2025年11月22日，周六"
  final String longAverage; // 平均睡眠时长 "6小时17分"
  final String shortAverage; // 平均小睡时长 "0小时9分"
  final List<DailySleepDetail> ringWeekOrMonthSleepVOS; // 每日睡眠详情列表

  WeekMonthSleepDetailData({
    required this.average,
    required this.dateStart,
    required this.dateEnd,
    required this.longAverage,
    required this.shortAverage,
    required this.ringWeekOrMonthSleepVOS,
  });

  factory WeekMonthSleepDetailData.fromJson(Map<String, dynamic> json) {
    final List<DailySleepDetail> details = [];
    if (json['ringWeekOrMonthSleepVOS'] != null && json['ringWeekOrMonthSleepVOS'] is List) {
      for (var item in json['ringWeekOrMonthSleepVOS']) {
        if (item != null && item is Map<String, dynamic>) {
          details.add(DailySleepDetail.fromJson(item));
        }
      }
    }

    return WeekMonthSleepDetailData(
      average: json['average']?.toString() ?? '--',
      dateStart: json['dateStart']?.toString() ?? '',
      dateEnd: json['dateEnd']?.toString() ?? '',
      longAverage: json['longAverage']?.toString() ?? '--',
      shortAverage: json['shortAverage']?.toString() ?? '--',
      ringWeekOrMonthSleepVOS: details,
    );
  }
}

/// 每日睡眠详情
class DailySleepDetail {
  final String dailyValue; // 日期值 "11/16" 或 "2"
  final List<SleepStageValue> weekOrMonthSleeps; // 睡眠阶段值列表 [清醒, 快速眼动, 浅睡眠, 深睡眠]

  DailySleepDetail({
    required this.dailyValue,
    required this.weekOrMonthSleeps,
  });

  factory DailySleepDetail.fromJson(Map<String, dynamic> json) {
    final List<SleepStageValue> sleeps = [];
    if (json['weekOrMonthSleeps'] != null && json['weekOrMonthSleeps'] is List) {
      for (var item in json['weekOrMonthSleeps']) {
        if (item != null && item is Map<String, dynamic>) {
          sleeps.add(SleepStageValue.fromJson(item));
        }
      }
    }

    return DailySleepDetail(
      dailyValue: json['dailyValue']?.toString() ?? '',
      weekOrMonthSleeps: sleeps,
    );
  }
}
